<template>
    <editor v-model="contentInfo" :init="tinymceInit" :disabled="false" @change="changeContent"
        api-key="gut7tnpt5zqsh4ov0eb8u85bqyub8vfo3cdso1bmw2h873s7" />
</template>
<script setup lang='ts'>
import Editor from '@tinymce/tinymce-vue';
import tinymce from 'tinymce';
import "tinymce/plugins/image";
import "tinymce/plugins/link";
import "tinymce/plugins/media";
import { fileUrl } from '@/config/common';

import { addOrEditFileInfoType } from '@/api/fileInfo/fileInfo/fileInfoTs';

interface Props {
    content?: string;
}

const props = defineProps<Props>();

const contentInfo = ref<string>();
// todo完善图片上传转url
const getCourseConfig = () => ({
    // selector: 'textarea', // change this value according to your HTML
    // skin: true,
    menubar: true,
    toolbar: true,
    // inline: true, //内联模式内容可继承页面的CSS样式
    branding: false,
    statusbar: false, // 隐藏编辑器底部的状态栏
    plugins:
        'preview importcss searchreplace autolink autosave save directionality code visualblocks visualchars fullscreen image link media codesample table charmap pagebreak nonbreaking anchor insertdatetime advlist lists wordcount help charmap quickbars emoticons',
    // theme: 'silver',
    // width: '100%',
    // height: 400,
    // keyboard: true, // 禁用键盘操作
    // offscreen: true, // 关闭 mce-offscreen-selection 特性
    // style_formats_merge: true,
    // style_formats_autohide: true,
    // contextmenu_never_use_native: true, // 在编辑器中屏蔽浏览器本身的右键菜单
    file_picker_types: 'image media',
    base_url: `/tinymce/`,
    language_load: true,
    language: 'zh_CN',
    language_url: `/tinymce/langs/zh_CN.js`,
    image_dimensions: false,
    image_description: false,
    image_uploadtab: true,// 本地上传按钮
    setup: function (editor) {
        editor.on('NodeChange', function (e) {
            if (e && e.element.nodeName.toLowerCase() === 'img') {
                e.element.removeAttribute('height');
                e.element.style.width = '100%';
            }
        });
        editor.on('OpenWindow', (e) => {
            const dialog = e.control;
            // 检查是否是图片插入对话框
            if (dialog && dialog.title === '插入/编辑图片') {
                console.log(`dialog`, dialog)
                // 查找并隐藏 "一般" 选项卡
                dialog.find('panel').forEach((panel) => {
                    const generalTab = panel.items.find((tab) => tab.name === 'general');
                    if (generalTab) {
                        generalTab.hide();
                    }
                });
            }
        });
    },
    height: 360,
    images_upload_handler: (blobInfo: any, success: any, failure: any) => new Promise((resolve, reject) => {
        console.log(`blobInfo`, blobInfo)
        // 使用 fetch 发送图片到后端服务器
        const formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());
        addOrEditFileInfoType('post', 'public', formData).then(async (res: any) => {
            if (res?.code == "200") {
                resolve(fileUrl + res?.data?.url);  // 服务器返回图片的 URL
            }
        }).catch(error => {
            reject('Image upload failed: ' + error.message);
        });
    }),
    media_live_embeds: true, // 支持视频嵌入实时预览
    media_dimensions: false,// 禁用宽高设置
    media_alt_source: false, // 禁用替代源输入
    media_poster: false, // 启用视频封面设置
    file_picker_callback: (callback, value, meta) => {
        if (meta.filetype === 'media') {
            const input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'video/*'); // 限制选择视频文件
            input.onchange = function () {
                const file = input.files?.[0];
                if (file) {
                    const formData = new FormData();
                    formData.append('file', file);
                    // 上传视频到服务器
                    addOrEditFileInfoType('post', 'public', formData)
                        .then((res: any) => {
                            if (res?.code === '200') {
                                const videoUrl = fileUrl + res.data.url;
                                callback(videoUrl, { title: file.name }); // 返回视频URL
                            } else {
                                console.error('视频上传失败');
                            }
                        })
                        .catch((err) => {
                            console.error('上传视频错误:', err.message);
                        });
                }
            };
            input.click();
        }
    },
    video_template_callback: (data) =>
        `<video width="100%" height="auto"${data.poster ? ` poster="${data.poster}"` : ''} controls="controls">\n` +
        `<source src="${data.source}"${data.sourcemime ? ` type="${data.sourcemime}"` : ''} />\n` +
        (data.altsource ? `<source src="${data.altsource}"${data.altsourcemime ? ` type="${data.altsourcemime}"` : ''} />\n` : '') +
        '</video>'
});

const eventMap = {
    init_instance_callback: (editor: any) => {
        editor.on('keydown', (event: any) => { });
        editor.on('mousedown', () => {
            tinymce.activeEditor?.mode.set('design');
            emit('update:content', contentInfo.value); // 发送内容给父组件
        });
        editor.on('contextmenu', (event: MouseEvent) => {
            event.preventDefault();
            const selection = tinymce.activeEditor?.selection;
            const content = selection?.getContent({ format: 'text' });
            if (!content) {
                return;
            }
        });
    },
};

const tinymceInit = {
    ...getCourseConfig(),
    ...eventMap,
};

const changeContent = () => {
    emit('changeContent', contentInfo.value);
}

const emit = defineEmits(['update:content', 'changeContent']);

watch(() => props.content,
    () => {
        contentInfo.value = props.content;
    }
);
</script>
<style lang='less' scoped></style>